<template>
  <!-- 自定义表单验证
        1：基本表单验证已完成
        2：rules:{
           prop的值:[
            ....,
            validator:(rule,value,callback)=>{
                // value:当前验证的值
                  callback: 验证成功 callback()     验证失败  callback(new Error('错误信息'))
            }
           ]
        }
 -->

  <div>
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input v-model="form.password2" show-password />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
      <el-form-item>
        <el-button @click="submit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        password: '',
        password2: '',
        mobile: ''
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const reg = /^1[3,9]\d{9}$/
              const bol = reg.test(value)
              // 验证某字符是否符合正则表达式，符合true,不符合false
              bol ? callback() : callback(new Error('请正确输入手机号'))
            },
            trigger: 'change'
          }
        ],
        password: [{ required: true, message: '必填', trigger: 'change' }],
        password2: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // rule:当前项的规则
              // value:当前项的值
              // callback:是否验证成功的回调函数
              //    验证成功  callback()
              //    验证失败  callback(new Error('错误信息'))
              if (value !== this.form.password) {
                callback(new Error('二次输入密码要一致'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs.form.validate((result) => {
        console.log(result)
      })
    }
  }
}
</script>

<style></style>
